package nl.vu.few.ibivu.biomodels.server;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import nl.vu.few.ibivu.biomodels.client.GatewayService;
import nl.vu.few.ibivu.biomodels.shared.AuthenticationProvider;
import nl.vu.few.ibivu.biomodels.shared.NotLoggedInException;
import nl.vu.few.ibivu.biomodels.shared.UserInfo;
import nl.vu.few.ibivu.biomodels.shared.UserProfile;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class GatewayServiceImpl extends RemoteServiceServlet implements GatewayService {
	private static final Map<AuthenticationProvider, String> openIdProviders;
	static {
		openIdProviders = new HashMap<AuthenticationProvider, String>();
		openIdProviders.put(AuthenticationProvider.GOOGLE, "google.com/accounts/o8/id");
		openIdProviders.put(AuthenticationProvider.YAHOO, "yahoo.com");
		openIdProviders.put(AuthenticationProvider.FACEBOOK, "facebook.com");
		openIdProviders.put(AuthenticationProvider.TWITTER, "twitter.com");
		openIdProviders.put(AuthenticationProvider.MYSPACE, "myspace.com");
		openIdProviders.put(AuthenticationProvider.AOL, "aol.com");
		openIdProviders.put(AuthenticationProvider.MYOPENID, "myopenid.com");
	}

	@Override
	public UserInfo getUserInfo(String requestURI) {
		UserService userService = UserServiceFactory.getUserService();
		UserInfo userInfo;
		Set<String> attributes = new HashSet<String>();
		attributes.add("openid.mode=checkid_immediate");
		attributes.add("openid.ns=http://specs.openid.net/auth/2.0");
		UserProfile userProfile;
		try {
			userProfile = new DAO().getOrCreateUserProfile();
		} catch (NotLoggedInException e) {
			userInfo = new UserInfo();
			userInfo.setLoggedIn(false);
			for (AuthenticationProvider ap : AuthenticationProvider.values()) {
				// (requestURI + "-" + openIdProviders.get(ap));
				userInfo.getLoginURL().put(
						ap,
						userService.createLoginURL(requestURI, null, openIdProviders.get(ap),
								attributes));
			}
			return userInfo;
		}
		userInfo = new UserInfo(userProfile);
		userInfo.setLoggedIn(true);
		userInfo.setLogoutURL(userService.createLogoutURL(requestURI));
		return userInfo;
	}

	@Override
	public void saveUserProfile(UserProfile userProfile)
			throws NotLoggedInException {
		DAO dao = new DAO();
		UserProfile realProfile = dao.getOrCreateUserProfile();
		realProfile.setFirstName(userProfile.getFirstName());
		realProfile.setLastName(userProfile.getLastName());
		realProfile.setSmartConnections(userProfile.useSmartConnections());
		dao.ofy().put(realProfile);
	}
}
